//
//  CitySearchViewController.m
//  ZAKER
//
//  Created by dllo on 15/8/27.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "CitySearchViewController.h"


@interface CitySearchViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UIAlertViewDelegate>

// 搜索的时候，存储城市名字和cityCode
@property (nonatomic, retain) EnterModel *cityModel;
@property (nonatomic, copy) NSDictionary *cityDic;

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *allCityArr;
@property (nonatomic, retain) NSMutableArray *hotCityArr;
@property (nonatomic, retain) NSMutableArray *myArray; // 存放已经分区好的数据, 搜索的数据源
@property (nonatomic, retain)  NSMutableArray *resultsData;//搜索结果数据
@property (nonatomic, retain) UISearchBar *mySearchBar; // 搜索城市
@property (nonatomic, retain) NSString *searchBarStr;
@property (nonatomic, retain) LocalData *localData; // 定位功能
@property (nonatomic, assign) NSInteger searchSection; // 保存我们找到的城市所在第几个分区
@property (nonatomic, assign) NSInteger  hotSection; // 标记是否有热门城市
@property (nonatomic, retain) MBProgressHUD *mb;
@property (nonatomic, retain) NSMutableArray *allArr;


@end

@implementation CitySearchViewController

-(void)dealloc
{
    [_allArr release];
    [_cityDic release];
    [_cityModel release];
    [_tableView release];
    [_allCityArr release];
    [_hotCityArr release];
    [_myArray release];
    [_resultsData release];
    [_mySearchBar release];
    [_searchBarStr release];
    [_localData release];
    [_mb release];
    
    _tableView.delegate = nil;
    
    [super dealloc];
    
}

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        
        self.allCityArr = [NSMutableArray array];
        self.hotCityArr = [NSMutableArray array];
        self.myArray = [NSMutableArray array];
        self.resultsData = [NSMutableArray array];
        self.allArr = [NSMutableArray array];
    }
    
    return self;
    
}


// 懒加载
- (LocalData *)localData
{
    if (_localData == nil) {
        
        self.localData = [[LocalData alloc] init];
    }
    
    return _localData;
    
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    [self createTableview];

    
    self.title = @"请选择你所在的城市";
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(left:)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    
    UIWindow *window = [[[UIApplication sharedApplication]delegate]window];
    self.mb = [[MBProgressHUD alloc]initWithView:window];
    [self.view addSubview:_mb];
    _mb.labelText = @"正在加载";
    [_mb show:YES];
    [_mb release];
    
    _searchSection = 10000; // 不要26以内的数,这个数是取section判断我们是搜索的tableView还是普通的tableView
 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)10 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        
        if (_mb != nil) {
            
            [_mb removeFromSuperview];
            
            UIAlertController *a = [UIAlertController alertControllerWithTitle:@"提示" message:@"数据加载失败" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                
            }];
            [a addAction:sure];
            // 模态推出
            [self presentViewController:a animated:YES completion:^{
                
            }];
            
        }
    });
    
    [self myConnection];
   [self createCustomView];
 
}

#pragma mark -
#pragma mark - navigation上的 "返回" 按钮
 
- (void)left:(UIBarButtonItem *)left
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}



#pragma mark - 数据解析

-(void)myConnection
{
    
    [MyAFNetworking GetWithURL:CitySearch dic:nil data:^(id responsder) {
        
        NSDictionary *dataDic = [responsder objectForKey:@"data"];
        self.allArr = [dataDic objectForKey:@"cities"]; // 存放所有城市的数组, 里面是多个字典
        
        NSArray *hotCityArr = [dataDic objectForKey:@"hot_cities"]; // 存放热门城市的数组, 里面是多个字典
        
        for (int i = 0; i < hotCityArr.count; i++) {
            
            EnterModel *hotCityModel = [[[EnterModel alloc]init] autorelease];
            [hotCityModel setValuesForKeysWithDictionary:hotCityArr[i]];
            [self.hotCityArr addObject:hotCityModel];
            
        }
        
        for (NSDictionary *dic in _allArr) {
            
            int flag = 0;
            
            for (NSDictionary *cityDic in self.myArray) {
                
                if ([[dic objectForKey:@"letter"] isEqualToString:[cityDic objectForKey:@"myLetter"]]) {
                    
                    NSMutableArray *cityArr = [cityDic objectForKey:@"arr"];
                    [cityArr addObject:dic];
                    flag = 1;
                    break;
                    
                }
            }
            
            if (flag == 0) {
                
                NSMutableArray *newArr = [NSMutableArray array];
                NSMutableDictionary *newDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:[dic objectForKey:@"letter"], @"myLetter",  newArr, @"arr", nil];
                [self.myArray addObject:newDic];
                
            }
        }
        
        [self.tableView reloadData];
        [_mb hide:YES];
        _mb = nil;
        
    }];
}

#pragma mark - 搜索和定位的自定义View

-(void)createCustomView
{
    
    self.mySearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(20 * myWidth, 20 * myHeight, self.view.frame.size.width - 40 * myWidth, 40 * myHeight)];
    _mySearchBar.placeholder = @"search"; // 占位符
    _mySearchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    [_mySearchBar sizeToFit];
    _mySearchBar.backgroundColor = RGBACOLOR(249.0, 249.0, 249.0, 1.0);
    _mySearchBar.backgroundImage = [self imageWithColor:[UIColor clearColor] size:_mySearchBar.bounds.size];
    _mySearchBar.delegate = self;
    [self.view addSubview:_mySearchBar];
    [_mySearchBar release];
    
}

#pragma mark - 点击事件







#pragma mark - searchBarb不颜色设置

- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

#pragma mark - 搜索关键字高亮

-(NSMutableAttributedString *)searchLightString:(NSString *)string light:(NSString *)light
{
    
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc]initWithString:string];
    
    for (int i = 0; i < attribute.length - light.length + 1; i++) {
        
        if ([[string substringWithRange:NSMakeRange(i, light.length)] isEqualToString:light]) {
            
            NSRange range = NSMakeRange(i, light.length);
            [attribute addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName: [UIFont boldSystemFontOfSize:17 * myHeight]} range:range];
            
        }
    }
    
    return [attribute autorelease];
    
}


#pragma mark - searchBar的协议方法

//searchBar开始编辑时改变取消按钮的文字
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    _mySearchBar.showsCancelButton = YES;
    
    for (id view in [_mySearchBar subviews]) {
        
        if ([view isKindOfClass:[UIButton class]]) {
            
            UIButton* cancelbutton = (UIButton* )view;
            [cancelbutton setTitle:@"取消" forState:UIControlStateNormal];
            break;
            
        }
    }
    
    return YES;
    
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    
    _mySearchBar.showsCancelButton = NO;
    
}

#pragma mark - 搜索按钮事件
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [_mySearchBar resignFirstResponder];
    _searchSection = 10000;
    self.searchBarStr = searchBar.text;
    
    
    for (NSInteger i = 0; i < [_myArray count]; i++) {
        NSDictionary *dic = _myArray[i];
        NSArray *arr = dic[@"arr"]; // 存城市名字
        for (NSDictionary *dic in arr) {
            NSString *cityName = dic[@"city_name"];
            
            if ([cityName isEqualToString:searchBar.text]) {
                self.searchSection = i;
                
#pragma mark - 在数组中寻找用户搜索到到城市
                self.cityDic = dic;
                
            }
        }
    }
    
    for (NSInteger j = 0; j  < [_hotCityArr count]; j++) {
        EnterModel *model  = _hotCityArr[j];
        NSString *str = model.city_name;
        if ([str isEqualToString:searchBar.text]) {
            _hotSection = 5000;
            
            
            self.cityModel = model;
        }
    }
    
    if (self.searchSection == 10000) {
        UIAlertController *a = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有该城市" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }];
        [a addAction:sure];
        // 模态推出
        [self presentViewController:a animated:YES completion:^{
            
        }];
        
    }
    
    [self.tableView reloadData];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    _mySearchBar.text = @"";
    
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @"";
    [_mySearchBar resignFirstResponder];
}


#pragma mark - 创建table, 以及实现协议方法

-(void)createTableview
{
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 85 , self.view.frame.size.width, self.view.frame.size.height - 64 - 100 * myHeight - 49) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [_tableView release];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (_searchSection == 10000) {
        
        if (section == 0) {
            return _hotCityArr.count;
            
        } else {
            
            NSDictionary *dic = _myArray[section - 1];
            NSMutableArray *arr = dic[@"arr"];
            return [arr count];
        }
        
    } else {
        return 1;
    }
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_searchSection == 10000) {
        
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"];
        
    }
    
    if (indexPath.section == 0) {
        
        // 热门城市
        EnterModel *model = [self.hotCityArr objectAtIndex:indexPath.row - _allCityArr.count];
        cell.textLabel.text = model.city_name;
        
    } else {
        
        NSDictionary *cityDic = [_myArray objectAtIndex:indexPath.section - 1];
        NSMutableArray *arr = cityDic[@"arr"];
        NSDictionary *dic = [arr objectAtIndex:indexPath.row] ;
        NSString *str =[dic objectForKey:@"city_name"];
        cell.textLabel.text = str;

    }
    if ([cell.textLabel.text rangeOfString:self.mySearchBar.text].location != NSNotFound) {
        
            cell.textLabel.attributedText = [self searchLightString:cell.textLabel.text light:self.mySearchBar.text];
        
        }
        
       return cell;
        
    } else {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
        if (cell == nil) {
            
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"];
            
        }
        
        cell.textLabel.text = self.searchBarStr;
        
        if ([cell.textLabel.text rangeOfString:self.mySearchBar.text].location != NSNotFound) {
            
            cell.textLabel.attributedText = [self searchLightString:cell.textLabel.text light:self.mySearchBar.text];
            
        }
        
        return cell;
        
    }
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    if (_searchSection == 10000) {
        return self.myArray.count + 1;
        
    } else
        if (_hotSection == 5000){
        
        return 2;
        
    } else {
        
        return 1;
        
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    // 如果我们是搜索的话,searchSection 应该有值
    if (_searchSection == 10000) {
        
        // 普通的section
        if (section == 0) {
            
            return @"热门城市";
            
        } else {
            
            NSString *str =[[self.myArray objectAtIndex:section - 1]objectForKey:@"myLetter"];
            return str;
            
        }
    } else if (_hotSection == 5000){
        
        if (section == 0) {
            
            return @"热门城市";
            
        } else {
            
        NSString *str =[[self.myArray objectAtIndex:_searchSection]objectForKey:@"myLetter"];
        return str;
            
        }
    } else {
        
        NSString *str =[[self.myArray objectAtIndex:_searchSection]objectForKey:@"myLetter"];
        return str;
        
    }
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    
     NSMutableArray *arr = [NSMutableArray array];
    [arr addObject:@"热"];
    
    for (int i = 0; i < _myArray.count; i++) {
        
        NSString *str = [[_myArray objectAtIndex:i] objectForKey:@"myLetter"];
        [arr addObject:str];
        
    }

    return arr;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    EnterModel *model = nil;
    NSDictionary *cityDic = nil;
    
    // 如果不是搜索的从数组里面取
    if (_searchSection == 10000) {
        
        if (indexPath.section == 0) {
            
            model = [_hotCityArr objectAtIndex:indexPath.row];
            [self.delegate sendCityName:model.city_name cityCode:model.city_code];
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            [user setObject:model.city_code forKey:@"cityCode"];
            
        }
        else {
            
            NSDictionary *dic = [_myArray objectAtIndex:indexPath.section - 1];
            NSArray *arr = [dic objectForKey:@"arr"];
            cityDic = [arr objectAtIndex:indexPath.row];
            [self.delegate sendCityName:cityDic[@"city_name"] cityCode:cityDic[@"city_code"]];
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            [user setObject:cityDic[@"city_code"] forKey:@"cityCode"];

        }
    }
    
    // 如果是搜索的话就是在搜索那给结果
    else {
        
        model = self.cityModel;
        cityDic = self.cityDic;
        
        if (model != nil) {
            
            [self.delegate sendCityName:model.city_name cityCode:model.city_code];
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            [user setObject:model.city_code forKey:@"cityCode"];
            
        }
        else { // 走字典
            
            [self.delegate sendCityName:cityDic[@"city_name"] cityCode:cityDic[@"city_code"]];
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            [user setObject:cityDic[@"city_code"] forKey:@"cityCode"];
            
        }

    }
    
#pragma mark - 虽然显示的是搜索的结果，但是你点击的是第一个row也就是数组中第一个元素。所以为什么搜索出来后点击回去还是北京
    
    // 如果热门有就走这个
   
    [self.navigationController popToRootViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
